﻿using System;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.Data.Common;
using System.Data.Linq;
using System.Globalization;
using System.Linq;
using System.ServiceModel.Syndication;
using System.Xml;
using mal.balades.Business.Log;
using Mal.Balades.AdminBusiness.DataModel;

namespace Mal.Balades.AdminBusiness.DataAccess
{
    public class AdminDataAccess
    {
        #region Fields

        #endregion

        #region Construction / Destruction
        public AdminDataAccess()
        {

        }
        #endregion

        #region enum, struct, class

        #endregion

        #region Properties

        #endregion

        #region Methods
        public ReadOnlyCollection<VisitDashboard> GetVisitsForDashboard()
        {
            MalLogManager.AdminLogger.Info("");

            List<VisitDashboard> results;

            try
            {
                using (BaladesAdminDataContext context = NewDataContext)
                {
                    results = context.VisitDashboards.ToList();
                }
            }
            catch (Exception exp)
            {
                MalLogManager.AdminLogger.Error(exp.Message, exp);
                throw;
            }

            MalLogManager.AdminLogger.InfoFormat("Number of visits : {0}", results.Count);
            return new ReadOnlyCollection<VisitDashboard>(results);
        }

        public VisitAdmin GetVisit(int visitId)
        {
            MalLogManager.AdminLogger.InfoFormat("visitId:{0}", visitId);
            VisitAdmin result;

            try
            {
                using (BaladesAdminDataContext context = NewDataContext)
                {
                    result = context.VisitAdmins.Where(v => v.VisitID == visitId).FirstOrDefault();
                }

                if (result == null)
                {
                    throw new ArgumentOutOfRangeException(string.Format(CultureInfo.InstalledUICulture, "There is no visit with visitId={0}", visitId));
                }
            }
            catch (Exception exp)
            {
                MalLogManager.AdminLogger.Error(exp.Message, exp);
                throw;
            }

            MalLogManager.AdminLogger.InfoFormat("visitId:{0}, title:{1}", visitId, result.Title);
            return result;
        }

        public ReadOnlyCollection<Picture> GetVisitPictures(int visitId)
        {
            MalLogManager.AdminLogger.InfoFormat("visitId:{0}", visitId);
            List<Picture> results;

            try
            {
                using (BaladesAdminDataContext context = NewDataContext)
                {
                    results = context.Pictures.Where(v => v.VisitID == visitId).ToList();
                }

            }
            catch (Exception exp)
            {
                MalLogManager.AdminLogger.Error(exp.Message, exp);
                throw;
            }
            MalLogManager.AdminLogger.InfoFormat("Number of pictures : {0}", results.Count);
            return new ReadOnlyCollection<Picture>(results);
        }

        public ReadOnlyCollection<Information> GetVisitInformations(int visitId)
        {
            MalLogManager.AdminLogger.InfoFormat("visitId:{0}", visitId);
            List<Information> results;

            try
            {
                using (BaladesAdminDataContext context = NewDataContext)
                {
                    results = context.Informations.Where(v => v.VisitID == visitId).ToList();
                }
            }
            catch (Exception exp)
            {
                MalLogManager.AdminLogger.Error(exp.Message, exp);
                throw;
            }
            MalLogManager.AdminLogger.InfoFormat("Number of informations : {0}", results.Count);
            return new ReadOnlyCollection<Information>(results);
        }

        public List<PictureType> GetPicturesTypes()
        {
            MalLogManager.AdminLogger.Info("");

            List<PictureType> results;
            try
            {
                using (BaladesAdminDataContext context = NewDataContext)
                {
                    results = context.PictureTypes.ToList();
                }
            }
            catch (Exception exp)
            {
                MalLogManager.AdminLogger.Error(exp.Message, exp);
                throw;
            }
            MalLogManager.AdminLogger.InfoFormat("Number of types : {0}", results.Count);

            return results;
        }

        public List<InformationType> GetInformationTypes()
        {
            MalLogManager.AdminLogger.Info("");

            List<InformationType> results;
            try
            {
                using (BaladesAdminDataContext context = NewDataContext)
                {
                    results = context.InformationTypes.ToList();
                }
            }
            catch (Exception exp)
            {
                MalLogManager.AdminLogger.Error(exp.Message, exp);
                throw;
            }
            MalLogManager.AdminLogger.InfoFormat("Number of types : {0}", results.Count);

            return results;
        }

        public List<Category> GetCategories()
        {
            MalLogManager.AdminLogger.Info("");

            List<Category> results;
            try
            {
                using (BaladesAdminDataContext context = NewDataContext)
                {
                    results = context.Categories.ToList();
                }
            }
            catch (Exception exp)
            {
                MalLogManager.AdminLogger.Error(exp.Message, exp);
                throw;
            }
            MalLogManager.AdminLogger.InfoFormat("Number of categories : {0}", results.Count);

            return results;
        }

        public SaveVisitResult SaveVisit(SaveVisitObject visitToSave)
        {
            MalLogManager.AdminLogger.Info(visitToSave);

            SaveVisitResult result = new SaveVisitResult();

            try
            {
                if (visitToSave == null)
                    throw new ArgumentNullException("visitToSave");

                if (visitToSave.Visit == null)
                    throw new InvalidOperationException("visitToSave.Visit should not be null");

                DbTransaction transaction = null;
                using (BaladesAdminDataContext context = NewDataContext)
                {
                    try
                    {
                        context.Connection.Open();
                        transaction = context.Connection.BeginTransaction();
                        context.Transaction = transaction;
                        if (visitToSave.Visit.VisitID.HasValue)
                        {
                            UpdateVisit(context, visitToSave.Visit);
                        }
                        else
                        {
                            InsertVisit(context, visitToSave.Visit);
                        }

                        if (!visitToSave.Visit.VisitID.HasValue)
                            throw new InvalidOperationException("visitToSave.Visit.VisitID must be not null after update.");

                        UpdateQuality(context, visitToSave.Visit);
                        UpdatePictures(context, visitToSave.Visit, visitToSave.Pictures);
                        UpdateInformations(context, visitToSave.Visit, visitToSave.Informations);

                        transaction.Commit();
                    }
                    catch (Exception exp)
                    {
                        MalLogManager.AdminLogger.Error("Rollback transaction.", exp);

                        // Rollback transaction
                        if (transaction != null)
                            transaction.Rollback();
                        throw;
                    }

                }

                result.VisitID = visitToSave.Visit.VisitID.Value;
            }
            catch (Exception exp)
            {

                MalLogManager.AdminLogger.Error(exp.Message, exp);
                throw;
            }

            return result;
        }

        public List<FeedAdmin> GetFeeds()
        {
            MalLogManager.BusinessLogger.InfoFormat("");

            List<FeedAdmin> results = new List<FeedAdmin>();
            using (BaladesAdminDataContext context = NewDataContext)
            {
                DataLoadOptions loadOptions = new DataLoadOptions();
                loadOptions.LoadWith<Feed>(f => f.FeedItems);

                context.LoadOptions = loadOptions;

                results = FeedAdmin.Convert(context.Feeds.ToList());
            }

            return results;
        }

        public void UpdateFeedItems(int feedId)
        {
            try
            {
                MalLogManager.BusinessLogger.InfoFormat("Load feedId {0}", feedId);
                using (BaladesAdminDataContext context = NewDataContext)
                {
                    DataLoadOptions loadOptions = new DataLoadOptions();
                    loadOptions.LoadWith<Feed>(v => v.FeedItems);
                    context.LoadOptions = loadOptions;

                    Feed feed = context.Feeds.First(f => f.FeedId == feedId);                    

                    XmlReader reader = XmlReader.Create(feed.Url);
                    SyndicationFeed syndicationFeed = SyndicationFeed.Load(reader);
                    List<FeedItem> feedItems = FeedItem.Convert(syndicationFeed.Items.ToList(), 5);

                    if (feedItems != null)
                    {
                        Feed trackedFeed = context.Feeds.First(f => f.FeedId == feed.FeedId);
                        trackedFeed.LastUpdate = DateTime.Now;

                        if (trackedFeed.FeedItems.Count() > 0)
                        {
                            context.FeedItems.DeleteAllOnSubmit(trackedFeed.FeedItems);
                        }

                        foreach (FeedItem item in feedItems)
                        {
                            item.Feed = trackedFeed;
                            if (item.PublishedDate.HasValue && item.PublishedDate.Value.Year < 2000)
                            {
                                item.PublishedDate = null;
                            }
                        }

                        context.FeedItems.InsertAllOnSubmit(feedItems);
                        context.SubmitChanges();
                    }
                }

            }
            catch (Exception exp)
            {
                MalLogManager.BusinessLogger.Error(
                        string.Format("Eror during load feed {0}, {1}", feedId, exp.Message), exp);

                throw;
            }
        }

        internal void UpdateVisit(BaladesAdminDataContext context, VisitAdmin visit)
        {
            context.balades_UpdateVisit(visit.VisitID, visit.PlaceCategoryID
                 , visit.MarketingCategoryID, visit.Title, visit.UrlName, visit.SumUp
                 , visit.Text, visit.Latitude, visit.Longitude, visit.Visible);
        }

        internal void InsertVisit(BaladesAdminDataContext context, VisitAdmin visit)
        {
            visit.VisitID = context.balades_InsertVisit(visit.PlaceCategoryID
                , visit.MarketingCategoryID, visit.Title, visit.UrlName, visit.SumUp
                , visit.Text, visit.Latitude, visit.Longitude, visit.Visible);
        }

        internal void UpdateQuality(BaladesAdminDataContext context, VisitAdmin visit)
        {
            context.balades_UpdateVisitQuality(visit.VisitID, visit.QualitySumUp, visit.QualityText
                , visit.QualityGps, visit.QualityPictures, visit.QualityInformations, visit.QualityCategories);
        }

        internal void UpdatePictures(BaladesAdminDataContext context, VisitAdmin visit
            , List<Picture> pictures)
        {
            context.balades_DeleteVisitPictures(visit.VisitID);

            foreach (Picture picture in pictures)
            {
                picture.PictureID = context.balades_InsertVisitPicture(picture.PictureTypeID, visit.VisitID
                    , picture.Title, picture.Text, picture.Url, picture.Rank);
            }
        }

        internal void UpdateInformations(BaladesAdminDataContext context, VisitAdmin visit
            , List<Information> informations)
        {
            context.balades_DeleteVisitInformations(visit.VisitID);

            foreach (Information information in informations)
            {
                information.InformationID = context.balades_InsertVisitInformation(information.InformationTypeID
                    , visit.VisitID, information.Text, information.Rank);
            }
        }

        internal BaladesAdminDataContext NewDataContext
        {
            get
            {
                return new BaladesAdminDataContext(mal.balades.Business.DataModel.BaladesDataContext.ConnectionString);
            }
        }
        #endregion

        #region Events

        #endregion
    }
}
